#include "ThreadPool.hpp"
#include "TcpServer.hpp"
#include <iostream>

using std::cout;
using std::endl;

//全局线程池
ln::ThreadPool gthreadpool(4,10);

class MyTask{
public:
    MyTask(const string & msg,ln::TcpConnectionPtr conn)
    :_msg(msg)
    ,_conn(conn)
    {

    }

    void process(){
        cout << "compute thread " << pthread_self()
             << ",MyTask::process is running..." << endl;

        //一些业务逻辑的处理
        string response(_msg);
        _conn->send(response);

        //Q:消息的发送应该在IO线程中完成，不应该在计算线程中完成
        //  4.0版本没有做到职责分离，需继续优化
    }

private:
    string               _msg;
    ln::TcpConnectionPtr _conn;
};

void onConnection(ln::TcpConnectionPtr conn){
    cout << "== version : Reactor V4.0 ==" << endl;
    cout << conn->toString() << " has connected successfully!" << endl;
}

void onMessage(ln::TcpConnectionPtr conn){
    //接收消息
    string msg = conn->receive();
    cout << "IO thread " << pthread_self()
         << " recv msg is " 
         << "== " << msg << " ==" << endl;
    
    //将消息封装成一个任务，交给线程池处理
    MyTask mytask(msg,conn);
    gthreadpool.addTask(std::bind(&MyTask::process,mytask));
}

void onClose(ln::TcpConnectionPtr conn){
    cout << "== version : Reactor V4.0 ==" << endl;
    cout << conn->toString() << " has closed" << endl;
}

int main()
{
    //开始运行线程池
    gthreadpool.start();

    ln::TcpServer server(8000);
    printf("server start listening...\n");

    //设置三个回调函数
    server.setAllCallbacks(onConnection,onMessage,onClose);

    //服务器开启事件循环
    server.start();

    return 0;
}

